package com.example.sunsg.okhttptest.retrofit;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import com.breadtrip.R;
import com.example.designmodel.StatusActivity;
import com.example.sunsg.okhttptest.annotation.TestReflect;
import com.example.sunsg.okhttptest.bean.KeyValue;
import com.example.sunsg.okhttptest.roobo.RooboLoginReq;
import com.example.sunsg.okhttptest.roobo.RooboLoginRsp;
import com.example.sunsg.okhttptest.rxjava.RxJavaActivity;
import com.example.sunsg.okhttptest.util.GsonUtil;
import com.example.sunsg.okhttptest.util.SecretUtil;
import com.example.sunsg.okhttptest.util.StorageUtils;
import com.example.sunsg.okhttptest.util.Util;

import java.io.File;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;
import retrofit2.http.GET;
import rx.Observable;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

public class RetrofitActivity extends AppCompatActivity {

    @BindView(R.id.btn_right)
    Button btnRight;

    public static void launch(Context context) {
        Intent intent = new Intent(context, RetrofitActivity.class);
        context.startActivity(intent);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_retrofit);
        ButterKnife.bind(this);
//        getToken();
//        rooboLogin();
//        dynamicProxy();
//        dynamicProxy2();
        rooboLginRxJava();
        invoke();
//        rooboLogin();

//        temp();
    }

    private void temp(){
        StorageUtils.readAndWriteLine("russa",StorageUtils.mkdir() +"/string.txt");
//        String [] array = "mc_not_found_msg,布丁序列号不存在,,".split(",");
//       int i =  array.length;
    }


    /***
     * get 请求
     */
    private void getToken() {
        Retrofit retrofit = new Retrofit.Builder()
                .client(OkHttp3ClientManager.mOkHttpClient)
                .baseUrl("http://api.breadtrip.com/android/bdchannel/")
                .addConverterFactory(GsonConverterFactory.create()).build();
        Ilogin login = retrofit.create(Ilogin.class);
        Call<Token> call = login.getAccessToken();
        call.enqueue(new Callback<Token>() {
            @Override
            public void onResponse(Call<Token> call, Response<Token> response) {
                Token token = response.body();
//                OkHttp3ClientManager.token = "Bearer "+token.getAccess_token();
                login();
            }

            @Override
            public void onFailure(Call<Token> call, Throwable t) {

            }
        });
    }

    /**
     * post 请求
     */
    private void login() {
        Retrofit retrofit = new Retrofit.Builder()
                .client(OkHttp3ClientManager.mOkHttpClient)
                .baseUrl("http://api.breadtrip.com/accounts/")
                .addConverterFactory(GsonConverterFactory.create()).build();
        Ilogin logins = retrofit.create(Ilogin.class);
        //获取签名
        List<KeyValue> list = new ArrayList<KeyValue>();
        KeyValue password = new KeyValue("password", "123456");
        KeyValue name = new KeyValue("username", "Sunsg11");
        list.add(password);
        list.add(name);
        String sign = SecretUtil.getSecretSign(list, getApplicationContext());

        Call<LoginResultBean> call = logins.login("Sunsg11", "123456", sign);
        call.enqueue(new Callback<LoginResultBean>() {
            @Override
            public void onResponse(Call<LoginResultBean> call, Response<LoginResultBean> response) {
                LoginResultBean loginResultBean = response.body();
//                loginResultBean.toString();
                String userId = "2387076450";
                String tripId = "2387148661";
//                getUserInfo();
                getSpotDetails();
            }

            @Override
            public void onFailure(Call<LoginResultBean> call, Throwable t) {
                if (t != null) {

                }
            }
        });
    }

    /**
     * get path
     */
    private void getUserInfo() {
        Retrofit retrofit = new Retrofit.Builder()
                .client(OkHttp3ClientManager.mOkHttpClient)
                .baseUrl("http://api.breadtrip.com/accounts/")
                .addConverterFactory(GsonConverterFactory.create()).build();
        Ilogin logins = retrofit.create(Ilogin.class);
        Call<UserInfo> call = logins.getUserInfo("2387076450");
        call.enqueue(new Callback<UserInfo>() {
            @Override
            public void onResponse(Call<UserInfo> call, Response<UserInfo> response) {
                UserInfo userInfo = response.body();
                UserInfo.DataBean dataBean = userInfo.getData();
                UserInfo.DataBean.TripsBean tripDataBeens = dataBean.getTrips();
                List<UserInfo.DataBean.TripsBean.TripDataBean> trips = tripDataBeens.getData();
                if (!trips.isEmpty()) {
                    UserInfo.DataBean.TripsBean.TripDataBean trip = trips.get(0);

                }

            }

            @Override
            public void onFailure(Call<UserInfo> call, Throwable t) {
                if (call != null) {

                }
            }
        });
    }

    private void getSpotDetails() {
        Retrofit retrofit = new Retrofit.Builder()
                .client(OkHttp3ClientManager.mOkHttpClient)
                .baseUrl("http://api.breadtrip.com/accounts/")
                .addConverterFactory(GsonConverterFactory.create()).build();
        Ilogin logins = retrofit.create(Ilogin.class);
        Call<SpotDetail> call = logins.getSpotDetail("2387670550");
        call.enqueue(new Callback<SpotDetail>() {
            @Override
            public void onResponse(Call<SpotDetail> call, Response<SpotDetail> response) {
                SpotDetail detail = response.body();
            }

            @Override
            public void onFailure(Call<SpotDetail> call, Throwable t) {

            }
        });
    }

    private void rooboLogin() {
        Retrofit retrofit = new Retrofit.Builder()
                .client(OkHttp3ClientManager.mOkHttpClient)
                .baseUrl("http://pd1s.roobo.net")
                .addConverterFactory(GsonConverterFactory.create()).build();
        Ilogin logins = retrofit.create(Ilogin.class);
        String json = Util.getFromAssets(getApplicationContext(), "roobo_login.txt");
        RooboLoginReq req = (RooboLoginReq) GsonUtil.fromJson(json, RooboLoginReq.class);
        Call<RooboLoginRsp> call = logins.rooboLogin(req);
        call.enqueue(new Callback<RooboLoginRsp>() {
            @Override
            public void onResponse(Call<RooboLoginRsp> call, Response<RooboLoginRsp> response) {
                RooboLoginRsp rsp = response.body();
            }

            @Override
            public void onFailure(Call<RooboLoginRsp> call, Throwable t) {

            }
        });
    }

    private void rooboLginRxJava(){
        Retrofit retrofit = new Retrofit.Builder()
                .client(OkHttp3ClientManager.mOkHttpClient)
                .baseUrl("http://pd1s.roobo.net")
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                .build();
        Ilogin logins = retrofit.create(Ilogin.class);
        String json = Util.getFromAssets(getApplicationContext(), "roobo_login.txt");
        RooboLoginReq req = (RooboLoginReq) GsonUtil.fromJson(json, RooboLoginReq.class);
        Observable<RooboLoginRsp> observable = logins.rooboLoginrxjava(req);
        observable
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<RooboLoginRsp>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onNext(RooboLoginRsp rooboLoginRsp) {
                        Log.i("test","Thread.currentThread().getName() rooboLoginRsp=" +Thread.currentThread().getName());
                        if(rooboLoginRsp != null){
                            rooboLoginRsp.getData();
                        }
                    }
                });

    }

    //============================== Dynamic 1==========================================================
    private void dynamicProxy() {
        ProxyedInterFace proxyedObject = new RealProxyed();

        ProxyObject proxyObject = new ProxyObject();
        proxyObject.setTargetObject(proxyedObject);
        InvocationHandler handler = proxyObject;

        Object object = Proxy.newProxyInstance(ProxyedInterFace.class.getClassLoader(), new Class[]{ProxyedInterFace.class}, handler);
        if (object != null) {
            ProxyedInterFace face = (ProxyedInterFace) object;
            face.proxyMethod();
            face.proxyMethod2();
        }
    }

    @OnClick(R.id.btn_right)
    public void onClick() {
        Log.i("test","btnright");
        RxJavaActivity.launch(RetrofitActivity.this);
    }

    public static interface ProxyedInterFace {
        void proxyMethod();

        void proxyMethod2();
    }

    public static class RealProxyed implements ProxyedInterFace {
        @Override
        public void proxyMethod() {
            Log.i("test", "我被代理了");
        }

        @Override
        public void proxyMethod2() {
            Log.i("test", "我被代理了222");
        }
    }

    public static class ProxyObject implements InvocationHandler {
        private Object targetObject;

        public void setTargetObject(Object targetObject) {
            this.targetObject = targetObject;
        }

        @Override
        public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
            return method.invoke(targetObject, args);
        }
    }

    //============================== Dynamic 1==========================================================

    //============================== Dynamic 2==========================================================
    public void dynamicProxy2() {
        ITest iTest = (ITest) Proxy.newProxyInstance(ITest.class.getClassLoader(), new Class[]{ITest.class}, new InvocationHandler() {
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                int a = (int) args[0];
                int b = (int) args[1];
                String methodName = method.getName();
                GET get = method.getAnnotation(GET.class);
                Log.i("test", "dynamic 2   a = " + a + " b = " + b + " method.name = " + methodName + " annotation Value = " + get.value());
                return null;
            }
        });
        iTest.add(3, 5);
    }

    public static interface ITest {
        @GET("start")
        void add(int a, int b);
    }

    //============================== Dynamic 2==========================================================


    //==============================


    private void invoke(){
        try {
            KeyValue keyValue1 = new KeyValue("KEY","VALUE");
            Class keyValue = KeyValue.class;
            Method method = keyValue.getDeclaredMethod("toast",Context.class);
            method.setAccessible(true);
            method.invoke(keyValue1,getApplicationContext());

            Class<?> object = Class.forName("com.example.sunsg.okhttptest.annotation.TestReflect");
            Field file = object.getDeclaredField("loginResultBean");
            file.setAccessible(true);
            Object key = file.get(null);
            if(key != null){
                if(key instanceof  String){
                    String ks = (String) key;
                    if(ks != null){

                    }
                }
            }
            Class<?> activityThreadClazz = Class.forName("android.app.ActivityThread");
            Object activityThread = null;
//            try {
                activityThread = null;
                  Field file1  =  activityThreadClazz.getDeclaredField("sCurrentActivityThread");
                  file1.setAccessible(true);

                activityThread = file1.get(null);
//            } catch (Exception e) {
//                // ignored
//            }
//            if (activityThread == null) {
                Field file2  =  activityThreadClazz.getDeclaredField("sThreadLocal");
                file2.setAccessible(true);
                activityThread = file2.get(null);

//            }
//            sActivityThread = activityThread;

        }  catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        }
    }

    public static class AA{
        private void test1(Context context){
            Toast.makeText(context,"test",Toast.LENGTH_SHORT).show();
        }

        private void tests2(BB b){
            b.testbb1();
        }
    }

    public static class BB{
        public void testbb1(){
            Log.i("test","bbbb111");
        }
    }

}
